package org.gongliang.jsmile.authc.sys.service;

import java.util.List;
import java.util.Map;

import org.gongliang.jsmile.authc.sys.dao.SysRoleDao;
import org.gongliang.jsmile.authc.sys.dao.SysUserDao;
import org.gongliang.jsmile.authc.sys.entity.SysUser;
import org.gongliang.jsmile.authc.sys.entity.SysUserRole;
import org.gongliang.jsmile.authc.sys.vo.SysUserVo;
import org.gongliang.jsmile.common.base.CRUDService;
import org.gongliang.jsmile.common.kit.BeanKit;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.google.common.collect.Lists;

/**
* 
* @author 龚亮
* @version 1.0
* @date 2018年08月25日 04:57:24
*/
@Service
public class SysUserService extends CRUDService<SysUserDao, SysUser> {

	@Autowired
	private SysRoleDao roleDao;
	/**
	 * desc:用户密码修改
	 * 
	 * @param userId
	 *            用户id
	 * @param password
	 *            原始密码
	 * @param newPassword
	 *            新密码
	 * @return
	 */
	@Transactional(readOnly = false, rollbackFor = Exception.class)
	public boolean updatePassword(Integer userId, String password, String newPassword) {
		return retBool(baseDao.updatePassword(userId, password, newPassword));
	}

	/**
	 * 根据用户名查找用户
	 */
	@Transactional(readOnly = true, rollbackFor = Exception.class)
	public SysUserVo findUser(String username) {
		return baseDao.findUser(username);
	}

	@Transactional(readOnly = true, rollbackFor = Exception.class)
	public List<SysUserVo> findAllByVo(Map<String, Object> reqMap) {
		return baseDao.findAllByVo(reqMap);
	}

	/**
	 * desc: 添加或修改用户
	 * @param user
	 * @return
	 */
	@Transactional(readOnly = false, rollbackFor = Exception.class)
	public boolean saveORupdate(SysUserVo user) {
		SysUser sysUser=BeanKit.classMap(SysUserVo.class,SysUser.class).map(user, SysUser.class);
		int i=0;
		if(null==user.getId()) {
			i+=baseDao.saveOne(sysUser);
		}else {
			i+=baseDao.updateById(sysUser);
		}
		if(null!=user.getRoleId()) {
			List<Integer> roleIds=Lists.newArrayList();
			roleIds.add(user.getRoleId());
			if(retBool(i)) {
				return saveUserRole(sysUser.getId(),roleIds);
			}
		}
		return retBool(i);
	}
	
	/**
	 * desc: 保存用户角色信息
	 * @param userId
	 * @param roleIds
	 * @return
	 */
	@Transactional(readOnly = false, rollbackFor = Exception.class)
	public boolean saveUserRole(Integer userId, List<Integer> roleIds) {
		int i = roleDao.deleteUserRole(userId);
		if (roleIds != null && roleIds.size() > 0) {
			for (int roleId : roleIds) {
				SysUserRole ur = new SysUserRole();
				ur.setUserId(userId);
				ur.setRoleId(roleId);
				i += roleDao.saveUserRole(ur);
			}
		}
		return retBool(i);
	}
}
